package com.ndood.admin.service.user.impl;

import java.util.Date;
import java.util.Optional;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.ndood.admin.core.constaints.AdminErrCode;
import com.ndood.admin.core.exception.AdminException;
import com.ndood.admin.pojo.system.UserPo;
import com.ndood.admin.repository.system.UserRepository;
import com.ndood.admin.service.user.AccountBindingService;

/**
 * 账号绑定相关业务
 */
@Service
public class AccountBindingServiceImpl implements AccountBindingService{

	@Autowired
	private UserRepository userDao;
	
	@Override
	public boolean isMobileBindingAccounts(String mobile) {
		Long count = userDao.countByMobile(mobile);
		return count > 0;
	}

	@Override
	public void bindingMobile(String userId, String mobile) throws AdminException {
		// Step1: 根据userId查询出用户
		Optional<UserPo> option = userDao.findById(Integer.parseInt(userId));
		if(!option.isPresent()) {
			throw new AdminException(AdminErrCode.ERR_OTHER,"用户不存在！");
		}
		
		// Step2: 更新用户信息
		UserPo userPo = option.get();
		userPo.setMobile(mobile);
		userPo.setUpdateTime(new Date());
		userDao.save(userPo);
	}

	@Override
	public boolean isEmailBindingAccounts(String email) {
		Long count = userDao.countByEmail(email);
		return count > 0;
	}

	@Override
	public void bindingEmail(String userId, String email) throws AdminException {
		// Step1: 根据userId查询出用户
		Optional<UserPo> option = userDao.findById(Integer.parseInt(userId));
		if(!option.isPresent()) {
			throw new AdminException(AdminErrCode.ERR_OTHER,"用户不存在！");
		}
		
		// Step2: 更新用户信息
		UserPo userPo = option.get();
		userPo.setEmail(email);
		userPo.setEmailStatus(0);
		userPo.setUpdateTime(new Date());
		userDao.save(userPo);
	}

}
